"""
大麦网App登录模块
支持账号密码登录和扫码登录（移动端版本）
"""

import time
import logging
from typing import Optional, Dict, Any, Union
from utils.mobile_driver_base import MobileDriverBase
from utils.common_utils import random_sleep, play_notification_sound


class DamaiLogin:
    """大麦网App登录处理类"""

    def __init__(self, mobile_driver: MobileDriverBase, config: Dict[str, Any]):
        self.driver = mobile_driver
        self.config = config
        self.logger = logging.getLogger("DamaiLogin")

        # 大麦App相关信息
        self.app_package = config.get("mobile", {}).get("app_package", "cn.damai")

    def login(self) -> bool:
        """执行登录流程"""
        try:
            # 启动大麦App
            if not self.driver.start_app(self.app_package):
                self.logger.error("启动大麦App失败")
                return False

            # 检查是否已经登录
            if self._check_login_success():
                self.logger.info("用户已登录")
                return True

            # 尝试进入登录页面
            if not self._navigate_to_login():
                self.logger.error("无法进入登录页面")
                return False

            # 尝试账号密码登录
            if self._try_password_login():
                self.logger.info("账号密码登录成功")
                return True

            # 如果密码登录失败，尝试其他登录方式
            self.logger.info("尝试其他登录方式")
            if self._try_alternative_login():
                self.logger.info("登录成功")
                return True

            self.logger.error("所有登录方式都失败")
            return False

        except Exception as e:
            self.logger.error(f"登录过程出现异常: {e}")
            return False

    def _navigate_to_login(self) -> bool:
        """导航到登录页面"""
        try:
            # 等待App启动完成
            time.sleep(5)

            # 查找登录按钮或我的页面
            login_elements = [
                {"text": "登录"},
                {"text": "我的"},
                {"resourceId": "cn.damai:id/login"},
                {"description": "登录"},
                {"text": "立即登录"},
                {"className": "android.widget.Button", "textContains": "登录"},
            ]

            for element_info in login_elements:
                if self.driver.click_element(timeout=3, **element_info):
                    self.logger.info(f"点击登录入口成功: {element_info}")
                    time.sleep(2)
                    return True

            # 如果没有找到登录按钮，尝试点击右下角的"我的"标签
            if self.driver.click_text("我的"):
                time.sleep(2)
                # 再次查找登录按钮
                for element_info in login_elements:
                    if self.driver.click_element(timeout=3, **element_info):
                        return True

            return False

        except Exception as e:
            self.logger.error(f"导航到登录页面失败: {e}")
            return False

    def _try_password_login(self) -> bool:
        """尝试账号密码登录"""
        try:
            user_config = self.config.get("user", {})
            username = user_config.get("username", "")
            password = user_config.get("password", "")

            if not username or password:
                self.logger.warning("用户名或密码未配置，跳过密码登录")
                return False

            # 等待登录页面加载
            time.sleep(3)

            # 查找并点击密码登录选项
            password_login_options = [
                {"text": "密码登录"},
                {"text": "账号密码登录"},
                {"resourceId": "cn.damai:id/password_login"},
                {"textContains": "密码"},
            ]

            for option in password_login_options:
                if self.driver.click_element(timeout=2, **option):
                    self.logger.info("切换到密码登录")
                    break

            time.sleep(1)

            # 输入用户名
            username_selectors = [
                {"resourceId": "cn.damai:id/username"},
                {"resourceId": "cn.damai:id/phone"},
                {"className": "android.widget.EditText", "instance": 0},
                {"text": "请输入手机号"},
                {"description": "手机号"},
            ]

            username_entered = False
            for selector in username_selectors:
                if self.driver.input_text(username, **selector):
                    self.logger.info("用户名输入成功")
                    username_entered = True
                    break

            if not username_entered:
                self.logger.error("未找到用户名输入框")
                return False

            time.sleep(1)

            # 输入密码
            password_selectors = [
                {"resourceId": "cn.damai:id/password"},
                {"className": "android.widget.EditText", "instance": 1},
                {"text": "请输入密码"},
                {"description": "密码"},
            ]

            password_entered = False
            for selector in password_selectors:
                if self.driver.input_text(password, **selector):
                    self.logger.info("密码输入成功")
                    password_entered = True
                    break

            if not password_entered:
                self.logger.error("未找到密码输入框")
                return False

            time.sleep(1)

            # 点击登录按钮
            login_buttons = [
                {"text": "登录"},
                {"text": "立即登录"},
                {"resourceId": "cn.damai:id/login_btn"},
                {"className": "android.widget.Button", "textContains": "登录"},
            ]

            for button in login_buttons:
                if self.driver.click_element(timeout=2, **button):
                    self.logger.info("点击登录按钮")
                    break

            # 等待登录结果
            time.sleep(5)

            # 处理可能的验证步骤
            if self._handle_verification():
                return self._check_login_success()

            return False

        except Exception as e:
            self.logger.error(f"密码登录出错: {e}")
            return False

    def _try_alternative_login(self) -> bool:
        """尝试其他登录方式（微信、支付宝等）"""
        try:
            # 查找其他登录方式
            alternative_logins = [
                {"text": "微信登录"},
                {"text": "支付宝登录"},
                {"text": "淘宝登录"},
                {"textContains": "一键登录"},
            ]

            for login_option in alternative_logins:
                if self.driver.click_element(timeout=2, **login_option):
                    self.logger.info(f"尝试登录方式: {login_option}")

                    # 等待外部应用处理登录
                    self.logger.info("请在外部应用中完成登录，等待60秒...")
                    play_notification_sound()

                    # 等待登录完成
                    for _ in range(30):  # 检查30次，每次2秒
                        if self._check_login_success():
                            return True
                        time.sleep(2)

                    # 如果这种方式失败，尝试下一种
                    continue

            return False

        except Exception as e:
            self.logger.error(f"其他登录方式出错: {e}")
            return False

    def _handle_verification(self) -> bool:
        """处理各种验证（滑块、短信验证等）"""
        try:
            # 检查是否需要滑块验证
            slider_elements = [
                {"textContains": "滑动"},
                {"textContains": "拖动"},
                {"description": "滑块"},
            ]

            for slider_info in slider_elements:
                if self.driver.find_element(**slider_info):
                    self.logger.info("检测到滑块验证，请手动完成")
                    time.sleep(15)  # 给用户时间完成滑块
                    return True

            # 检查是否需要短信验证
            sms_elements = [
                {"textContains": "验证码"},
                {"text": "短信验证码"},
                {"resourceId": "cn.damai:id/verification_code"},
            ]

            for sms_info in sms_elements:
                if self.driver.find_element(**sms_info):
                    self.logger.info("需要短信验证码，请在60秒内手动输入")
                    time.sleep(60)
                    return True

            return True

        except Exception:
            # 没有验证步骤
            return True

    def _check_login_success(self) -> bool:
        """检查是否登录成功"""
        try:
            # 等待页面加载
            time.sleep(3)

            # 查找登录成功的标识
            success_indicators = [
                {"textContains": "个人中心"},
                {"textContains": "我的订单"},
                {"textContains": "会员"},
                {"text": "设置"},
                {"resourceId": "cn.damai:id/user_avatar"},
                {"description": "用户头像"},
            ]

            for indicator in success_indicators:
                if self.driver.find_element(**indicator):
                    self.logger.info("检测到登录成功标识")
                    return True

            # 检查是否还在登录页面
            login_page_indicators = [
                {"text": "登录"},
                {"text": "立即登录"},
                {"text": "密码登录"},
                {"text": "验证码登录"},
            ]

            for indicator in login_page_indicators:
                if self.driver.find_element(**indicator):
                    return False  # 仍在登录页面

            # 如果既没有成功标识也没有登录页面标识，默认认为成功
            return True

        except Exception as e:
            self.logger.error(f"验证登录状态出错: {e}")
            return False

    def is_logged_in(self) -> bool:
        """检查当前是否已登录"""
        try:
            # 确保App在前台
            if not self.driver.is_app_running(self.app_package):
                self.driver.start_app(self.app_package)
                time.sleep(3)

            # 点击"我的"标签
            if self.driver.click_text("我的"):
                time.sleep(2)

            return self._check_login_success()

        except Exception:
            return False

    def logout(self) -> None:
        """退出登录"""
        try:
            # 进入个人中心
            if not self.driver.click_element(text="我的"):
                return

            time.sleep(2)

            # 查找设置按钮
            settings_elements = [
                {"text": "设置"},
                {"resourceId": "cn.damai:id/settings"},
                {"description": "设置"},
            ]

            for setting in settings_elements:
                if self.driver.click_element(timeout=2, **setting):
                    time.sleep(2)
                    break

            # 查找退出登录按钮
            logout_elements = [
                {"text": "退出登录"},
                {"text": "注销"},
                {"textContains": "退出"},
            ]

            for logout_btn in logout_elements:
                if self.driver.click_element(timeout=2, **logout_btn):
                    self.logger.info("退出登录成功")
                    break

        except Exception as e:
            self.logger.error(f"退出登录失败: {e}")
